package de.slothsoft.wasbinich.core.database.webservice;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;

import de.slothsoft.wasbinich.core.database.DatabaseException;
import de.slothsoft.wasbinich.core.database.DatabaseExceptionCode;

public final class WebserviceUtil {

    protected static final Gson GSON = new GsonBuilder()
	    .registerTypeAdapter(String[].class, new StringArrayTypeAdapter()).enableComplexMapKeySerialization()
	    .create();

    public static DatabaseException createDatabaseException(String errorJson) {
	try {
	    WebserviceError error = GSON.fromJson(errorJson, WebserviceError.class);
	    DatabaseExceptionCode code = DatabaseExceptionCode.fromValue(error.code);
	    return new DatabaseException(code, error.message);
	} catch (JsonSyntaxException e) {
	    System.err.println("Error in WebserviceUtil.createDatabaseException(): " + errorJson); //$NON-NLS-1$
	    throw e;
	}
    }

    public static DatabaseException createOAuth2Exception(String errorJson) {
	try {
	    OAuth2Error error = GSON.fromJson(errorJson, OAuth2Error.class);
	    DatabaseExceptionCode code = DatabaseExceptionCode.fromValue(error.error.toUpperCase());
	    return new DatabaseException(code, error.error_description);
	} catch (JsonSyntaxException e) {
	    System.err.println("Error in WebserviceUtil.createOAuth2Exception(): " + errorJson); //$NON-NLS-1$
	    throw e;
	}
    }

    private WebserviceUtil() {
	// hit me baby one more time
    }
}
